import pymysql


class MySQLDB:
    # 建立数据库连接
    def __init__(self):
        self.con = pymysql.connect(
            user="root",
            password="Admin@888",
            host='192.168.1.9',
            database='brtc_api',
            port=3306,
            autocommit=True
        )

        self.cursor = self.con.cursor()

        # 获取一条记录
    def get_one_data(self, sql1):
        try:
            # sql = "select * from dept where dname = 'SALES'"
            # 执行sql语句
            self.cursor.execute(sql1)
            # 获取到游标中查询的数据
            return self.cursor.fetchone()
        except Exception as e:
            print(f"SQL执行时失败,失败原因是：{e}")

    # 获取所有记录
    def get_all_data(self, sql2):
        try:
            sql = "select * from dept"
            self.cursor.execute(sql2)
            return self.cursor.fetchall()
        except Exception as e:
            print(f"SQL执行时失败,失败原因是：{e}")

        # 获取指定条数记录
    def get_data_limit(self, sql2):
        try:
            sql = "select * from dept"
            self.cursor.execute(sql2)
            return self.cursor.fetchmany(2)
        except Exception as e:
            print(f"SQL执行时失败,失败原因是：{e}")

    # 修改,新增,删除数据
    def execute_data(self, insert_sql):
        try:
            self.cursor.execute(insert_sql)
            # 提交数据
            self.con.commit()
            return True
        except Exception as e:
            print(f"SQL执行时失败,失败原因是：{e}")

    # 有条件的查询sql
    def sql_where(self, key, value):
        return f"select * from dept where {key}='{value}'"

    # 无条件的sql
    def sql_all(self):
        return f"select * from dept"

    # 释放数据库连接
    def __del__(self):
        self.cursor.close()
        self.con.close()

# 实例化MySQLDB
mysql_db = MySQLDB()